// b2c/submit/submit.js
const md5 = require('../../js/md5.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cookie:null,
    https:"https://csb2c.fenxiangqu.cn/",
    payArray:{
        chils: ["微信支付", "货到付款"],
        val: ["1", "2"]
    },
    options:{},
    payIndex:0,
    shipping:{
        index:[],
        value:[]
    },
    shipContext:{
      index:[],
      value:[]
    },
    spid:"",
    shipContextIndex:0,
    shipshow:false,
    ship:"快递",
    shippingIndex:0,
    _dzname: app.globalData._dzname,
    addressId:"",
    _dzphone:"",
    _dzaddress:"",
    newAddress:"请新建收货地址以确保商品顺利到达!",
    addtoggle:false,
    dateof:[],
    pickerVal:[0,0],
    dateshow:false,
    faShow:false,
    prov:"",
    yhje:0,
    ts:'没有',
    tsshow:false,
    all_w_id:"",
    nm:0,
    faCon:[
      { name: "个人", value:"个人",checked:'true'},
      { name: "公司", value:"公司"}
    ],
    fpinput:"",
    orderallprice: app.globalData.orderallprice,
    all_price: app.globalData.all_price,
    yhj: app.globalData.yhj,
    kg: app.globalData.kg,
    yun_price: app.globalData.yun_price,
    _amount_obj:"",/*起送金额 */
    yhjtext: app.globalData.yhjtext,
    fptoggle:"个人",
    fptt:"",
    tccomm:[]/*组合套餐 */,
    jqgcomm: [] ,/*加钱购 */
    buying:[],
    comm:[],
    full:[],
    red:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.globalData.user_yhq = "";
    app.globalData.yhj = "00.00"
    wx.setNavigationBarTitle({
      title: '确认订单'
    })
    const self = this,a = wx.getStorageSync('cookie') || [];
    let spid;
    this.setData({
      cookie: a,
      options: options,
      _gmtype: options.gmtype,
      yhj:'00.00'
    })
    if (options.type === "comm"){
      spid = {
        l: options.spidlist,
        n: options.num | 0
      }
      this.data.spid = spid
    }else{
      spid = {
        l: options.spidlist
      }
      this.data.spid = spid
    }
    
    
  },
  fptt(res){
    this.data.fptt = res.detail.value;
    console.log(res.detail.value)
  },
   /*加载商品*/
  adding(obj, callback){
    const self = this, post = this.data.options.type;
    wx.request({
      url: "https://csb2c.fenxiangqu.cn/" + (post === "comm" ? "xcx_50005_1_wx" :"xcx_50005_wx"),
      data: obj,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': "LID=" + self.data.cookie
      },
      method: "POST",
      success: (res) => {
        callback && callback(res)
      },
      fail: (res) => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'success',
          duration: 1000
        })
      }
    })
  },
  /*加载收货地址*/
  addAddress(_dzname, callback){
    const self =  this;
    if (!_dzname){
      wx.request({
        url: "https://csb2c.fenxiangqu.cn/xcx_ss_0000012s",
        data: {
          a: ""
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'Cookie': "LID=" + this.data.cookie
        },
        method: "POST",
        success: (res) => {
          callback && callback(res)
        },
        fail: (res) => {
          wx.showToast({
            title: '网络请求失败',
            icon: 'success',
            duration: 1000
          })
        }
      })
    }
  },
  /*加载配送方式*/
  addShipping( callback ){
      wx.request({
        url: "https://csb2c.fenxiangqu.cn/xcx_Distribution",
        data: {
          a: ""
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'Cookie': "LID=" + this.data.cookie
        },
        method: "POST",
        success: (res) => {
          callback && callback(res)
        },
        fail: (res) => {
          wx.showToast({
            title: '网络请求失败',
            icon: 'success',
            duration: 1000
          })
        }
      })
  },
  urladdress(res){
    app.globalData.nt = "";
    wx.navigateTo({
      url: '../address/address',
    })
  },
  /*加载门店自提地址*/
  addSer( callback ){
    const self = this;
    wx.request({
      url: "https://csb2c.fenxiangqu.cn/xcx_ss_000012s",
      data: {
        a: ""
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': "LID=" + this.data.cookie
      },
      method: "POST",
      success: (res) => {
        callback && callback(res)
      },
      fail: (res) => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'success',
          duration: 1000
        })
      }
    })
  },
  /*选择快递运送方式*/
  sb(kg,callback){
    const self = this;
    let all_zj = 0;
    wx.request({
      url: "https://csb2c.fenxiangqu.cn/xcx_submit_kd",
      data: {
        a: ""
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': "LID=" + this.data.cookie
      },
      method: "POST",
      success: (res) => {
        console.log(res)
        let qrdd_kd = res.data[0].logistics, g_s = self.data.prov;
        if (g_s == "" || g_s == "null" || g_s == undefined) {
          callback && callback(0)
        } else {
          g_s = g_s.replace('省', "");
          if (qrdd_kd == "undefined" || qrdd_kd == ""){

            wx.showToast({
              title: '地区不支持派送',
              icon: 'success',
              duration: 3000
            })
            self.data.all_w_id = ""
            callback && callback(all_zj)
          }else{
            for (let i = 0; i < qrdd_kd.length; i++){
              if (qrdd_kd[i].city.indexOf(g_s) >= 0){
                
                if( +kg > 1){
                  
                  all_zj = Math.ceil(+kg - 1) * Number(qrdd_kd[i].c_weight) + Number(qrdd_kd[i].f_weight);  
                }else{
                  all_zj = Number(qrdd_kd[i].f_weight);
                }
                self.setData({ yun_price: all_zj.toFixed(2)})
                app.globalData.yun_price = all_zj.toFixed(2);
                self.data.all_w_id = qrdd_kd[i].guid;
                self.qrdd_end_jg();
                if (self.data.ship == "快递"){
                  var _all_price = +self.data.all_price;
                  var _yun_price = +self.data.yun_price;
                  var yhj = +self.data.yhj;
                  var yhje = +self.data.yhje;
                  self.updateQrdd(_all_price, "", _yun_price, _all_price + (+_yun_price) - yhj-yhje)
                  break;
                }
              }else{
                wx.showToast({
                  title: '地区不支持派送',
                  icon: 'success',
                  duration: 3000
                })
                self.data.all_w_id = ""
              }
            }
            callback && callback(all_zj)
          }
        }
      },
      fail: (res) => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'success',
          duration: 1000
        })
      }
    })
  },
  coupons( res ){
    wx.navigateTo({
      url: '../coupons/coupons?num=1'
    })
  },
  /*提交订单 */
  mongNum( res ){
    const self = this, data = self.data;
    let g = app.globalData;
    wx.showModal({
      title: '提示',
      content: '确认订单信息无误',
      success: function (ssss) {
        if (ssss.confirm) {
          if (data._amount_obj == "" || data.ship == '门店自提') {

          } else {
            console.log(data._amount_obj)
            wx.showToast({
              title: '订单未满起送金额',
              icon: 'success',
              duration: 1000
            })
            return;
          }
          let g_id = data.addressId;
          if (data.ship === "门店自提") {
            g_id = '123456789012345678901234';
          }
          if ((g_id == "null" || !g_id) && data.ship != "门店自提") {
            wx.showToast({
              title: '请选择收货地址',
              icon: 'success',
              duration: 1000
            })
          } else {

            if (data.all_w_id == "" || data.all_w_id == null || data.all_w_id == undefined) {
              if (data.ship == '门店自提') {
                if (data.shipContext.index[data.shipContextIndex] == '') {
                  wx.showToast({
                    title: '请选择自提地址',
                    icon: 'success',
                    duration: 1000
                  })
                  return;
                }
              } else if (data.ship == '定时配送') {

              } else if (data.ship == '立即配送') {

              } else {
                console.log(data.all_w_id)
                wx.showToast({
                  title: '地区不在配送范围',
                  icon: 'success',
                  duration: 1000
                })
                return;
              }

            }
            let tj = {
              psfs: data.ship,
              sp: [],
              tc: [],
              jqg: [],
              dzid: g_id,
              pay: data.payArray.chils[data.payIndex],
              fp: data.faShow,
              fplx: "",
              fptt: "",
              bz: data.fpinput,
              sp_count: data.all_price,
              sp_pay: data.orderallprice,
              rule: []
            };

            if (g.tc_obj.length > 0 && (data._gmtype == "tjdd" || data._gmtype == "ljgm")){
              for (let i = 0; i < g.tc_obj.length; i++){
                tj.tc.push({
                  packageId: g.tc_obj[i].packageId,
                  packageName: g.tc_obj[i].packageName,
                  packageNum: g.tc_obj[i].packageNum,
                  packageprice: g.tc_obj[i].packageprice,
                  assemblyImage:g.tc_obj[i].assemblyImage
                });
                console.log(g.tc_obj[i])
              }
            }
          
            if (g.jqg_obj.length > 0 && (data._gmtype == "tjdd" || data._gmtype == "ljgm")) {
              for (let i = 0; i < g.jqg_obj.length; i++) {
                tj.jqg.push({
                  _id: g.jqg_json[i]._id,
                  userQuota: g.jqg_json[i].userQuota,
                  spmc: g.jqg_json[i].spmc,
                  exchangePrice: g.jqg_json[i].exchangePrice,
                  sptm: g.jqg_json[i].sptm
                });
              }
            }


            if (g.zc_obj !== "") {
              for (let i = 0; i < g.zc_obj.length; i++) {
                if (!g.zc_obj[i].type) {
                  let _openJFDK = 0;
                  tj.sp.push({
                    spid: g.zc_obj[i].spid,
                    spsl: g.zc_obj[i].spsl,
                    spbh: g.zc_obj[i].spbh,
                    rule_id: g.zc_obj[i].rule_id,
                    rule_name: g.zc_obj[i].rule_name,
                    rule_count: g.zc_obj[i].rule_count,
                    rule_preferential: g.zc_obj[i].rule_preferential,
                    isCheckJFDK: _openJFDK
                  })
                }else{
                  tj.sp.push({
                    spid: g.zc_obj[i].spid,
                    spsl: g.zc_obj[i].spsl,
                    spbh: g.zc_obj[i].spbh,
                    rule_id: "",
                    rule_name: "",
                    rule_count: "",
                    rule_preferential: "",
                    type: g.zc_obj[i].type
                  })
                }
              }

              if (g.zc_obj.length > 0 && (data._gmtype == "tjdd" || data._gmtype == "ljgm")) {
                for (let i = 0; i < g._ab_obj.length; i++) {
                  tj.rule.push({
                    ruleid: g._ab_obj[i][0],
                    rule_num: g._ab_obj[i][1],
                    rule_preferential: g._ab_obj[i][2],
                    rule_total: g._ab_obj[i][3],
                    rule_name: g._ab_obj[i][4]
                  })
                }
              }
            }
            if (data.faShow) {
              if (data.fptoggle == "个人"){
                tj.fplx = "个人";
              }
              if (data.fptoggle == "公司"){
                tj.fplx = "公司";
              }
              if (data.fptt == ""){
                wx.showToast({
                    title: '请输入发票抬头',
                    icon: 'success',
                    duration: 2000
                  })
                return;
              }
            }
            var all_ps = false;
            all_ps = (data.ship == "" ? false : true);
            if (!all_ps) {
              wx.showToast({
                title: '不支持该配送方式',
                icon: 'success',
                duration: 2000
              })
            } else {
              if (data.ship == '门店自提' || data.ship == "定时配送" || data.ship == "立即配送") {
                tj.psid = data.shipContext.index[data.shipContextIndex];
               
              } else {
                tj.psid = data.all_w_id;
              }
            }
            wx.login({
              success: function (res) {
                if (res.code) {
                  //发起网络请求
                  wx.request({
                    url: 'https://csb2c.fenxiangqu.cn/xcxonLogin',
                    data: {
                      code: res.code
                    },
                    method: "POST",
                    success(res) {
                      console.log(data.all_price)
                      const openid = res.data;
                      wx.request({
                        url: "https://csb2c.fenxiangqu.cn/xcx_50008_wx",
                        data: {
                          q: JSON.stringify(tj),
                          t: data._gmtype,
                          g: openid,
                          y: app.globalData.user_yhq,
                          e: +data.all_price,
                          isCheckJFDK:false,
                          walletNum:0,
                          source: 'wx'
                        },
                        header: {
                          'content-type': 'application/x-www-form-urlencoded',
                          'Cookie': "LID=" + self.data.cookie
                        },
                        method: "POST",
                        success: (ts) => {
                          if (ts.data == "err") {
                            wx.showToast({
                              title: '提交订单失败!',
                              icon: 'success',
                              duration: 2000
                            })
                            wx.redirectTo({
                              url: '../goods/goods'
                            })
                          } else if (+ts.data == 0) {
                            wx.showToast({
                              title: '支付异常[001]!',
                              icon: 'success',
                              duration: 2000
                            })
                            wx.redirectTo({
                              url: '../goods/goods'
                            })
                          } else if (ts.data == "no xl") {
                            wx.showToast({
                              title: '限量活动已失效!',
                              icon: 'success',
                              duration: 2000
                            })
                            wx.redirectTo({
                              url: '../goods/goods'
                            })
                          } else if (ts.data == "no xs") {
                            wx.showToast({
                              title: '限时活动已失效!',
                              icon: 'success',
                              duration: 2000
                            })
                            wx.redirectTo({
                              url: '../goods/goods'
                            })
                          } else if (+ts.data == 1) {
                            wx.showToast({
                              title: '部分商品停售!',
                              icon: 'success',
                              duration: 2000
                            })
                            wx.redirectTo({
                              url: '../goods/goods'
                            })
                          } else if (+ts.data == 2) {
                            wx.showToast({
                              title: '部分商品停售!',
                              icon: 'success',
                              duration: 2000
                            })
                            wx.redirectTo({
                              url: '../goods/goods'
                            })
                          } else {
                            const json = ts.data;
                            if (json.ret == "wx") {
                              console.log(json)
                              wx.request({
                                url: 'https://csb2c.fenxiangqu.cn/xcx_pay',
                                data: {
                                  orderid: json.orderNum,
                                  openid: openid,
                                  price: data.orderallprice
                                },
                                method: "POST",
                                header: {
                                  'content-type': 'application/json',
                                  'Cookie': "LID=" + self.data.cookie // 默认值
                                },
                                success: function (pay) {
                                  
                                  const appId = pay.data.appId, timeStamp = (Date.parse(new Date()) / 1000).toString(),
                                    pkg = Math.random().toString(36).substr(2), id = pay.data.package;
                                  wx.requestPayment({
                                    appId: appId,
                                    timeStamp: timeStamp,
                                    nonceStr: pkg,
                                    "package": "" + id + "",
                                    signType: "MD5",
                                    paySign: md5.hexMD5('appId=' + appId + '&nonceStr=' + pkg + '&package=' + id + '&signType=MD5&timeStamp=' + timeStamp + "&key=SYHLKJSYHLKJSYHLKJSYHLKJSYHLKJ00").toUpperCase(),
                                    success(res) {
                                      if (res.errMsg == "requestPayment:ok") {
                                        wx.showToast({
                                          title: '支付成功!',
                                          icon: 'success',
                                          duration: 3000
                                        })
                                        wx.switchTab({
                                          url: '../home/home',
                                        })
                                      } else {
                                        wx.showToast({
                                          title: '支付失败!',
                                          icon: 'success',
                                          duration: 3000
                                        })
                                        wx.switchTab({
                                          url: '../center/center',
                                        })
                                      }
                                    },
                                    fail(res) {
                                      wx.showToast({
                                        title: '下单失败!',
                                        icon: 'success',
                                        duration: 3000
                                      })
                                      wx.switchTab({
                                        url: '../center/center',
                                      })
                                    }
                                  })
                                },
                                fail: function (res) {
                                  wx.showToast({
                                    title: '网络请求失败',
                                    icon: 'success',
                                    duration: 1000
                                  })
                                }
                              })
                            } else if (json.ret == "hdfk") {
                              wx.request({
                                url: 'https://csb2c.fenxiangqu.cn/xcx_orderERP',
                                data: {
                                  orderid: json.orderNum
                                },
                                method: "POST",
                                header: {
                                  'content-type': 'application/json',
                                  'Cookie': "LID=" + self.data.cookie // 默认值
                                },
                                success: function (res) {
                                },
                                fail: function (res) {
                                  wx.showToast({
                                    title: '网络请求失败',
                                    icon: 'success',
                                    duration: 1000
                                  })
                                }
                              })
                              wx.request({
                                url: 'https://csb2c.fenxiangqu.cn/xcx_zfcallback',
                                data: {
                                  orderid: json.orderNum
                                },
                                method: "POST",
                                header: {
                                  'content-type': 'application/json',
                                  'Cookie': "LID=" + self.data.cookie // 默认值
                                },
                                success: function (res) {
                                },
                                fail: function (res) {
                                  wx.showToast({
                                    title: '网络请求失败',
                                    icon: 'success',
                                    duration: 1000
                                  })
                                }
                              })
                              wx.showToast({
                                title: '下单成功,等待收货',
                                icon: 'success',
                                duration: 2000
                              })
                              wx.redirectTo({
                                url: '../order/order?itype=',
                              })
                            }
                          }
                        },
                        fail: (res) => {
                          wx.showToast({
                            title: '网络请求失败',
                            icon: 'success',
                            duration: 1000
                          })
                        }
                      })
                    },
                    fail(res) {
                      console.log(res)
                    }
                  })
                } else {
                  console.log('登录失败！' + res.errMsg)
                }
              }
            });


          }

        } else if (ssss.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  bindPickerplay( res ){
    this.setData({
      payIndex: res.detail.value | 0
    })
  },
  bindPickerShip( res ){
    const self = this;
    self.setData({
      shippingIndex: res.detail.value | 0,
      ship: self.data.shipping.index[res.detail.value | 0]
    })
    if (this.data.ship == "门店自提" ){
      this.addSer(res=>{
        app.globalData.yun_price = '0.00';
        self.setData({ yun_price: '0.00' })
        const _all_price = +self.data.all_price, _yun_price = +self.data.yun_price, yhj = +self.data.yhj, yhje = +self.data.yhje;
        self.updateQrdd(_all_price, "", 0, (+_all_price) - (_yun_price) - yhj - yhje);
        self.setData({
          shipContext: {
            index:res.data.map(item => {
              return `${item.sheng}${item.city}${item.qu}${item.address}`
            }),
            value:res.data.map(item=>{
              return item["_id"]
            })
            },
          shipshow:true,
          dateshow:false,
          fpinput:""    
        })
      }) 

    } else if (this.data.ship == "立即配送"){
      app.globalData.yun_price = '0.00';
      self.setData({ yun_price: '0.00' })
      const _all_price = +self.data.all_price, _yun_price = +self.data.yun_price, yhj = +self.data.yhj, yhje = +self.data.yhje;
      self.updateQrdd(_all_price, "", 0, (+_all_price) - (_yun_price) - yhj - yhje);
      self.setData({
        shipshow: false,
        dateshow: false,
        fpinput:""
      })
    } else if(this.data.ship == "快递"){
      self.sb(self.data.kg, result => {
        self.setData({
          shipshow: false,
          dateshow: false,
          fpinput:""
        })
      })
    } else if(this.data.ship == "定时配送"){
      let dateofArray = [[],[]];
      for(let i = 0; i < 7; i++){
        const DC = 86400000, daof = new Date(i*DC + Date.now());
        dateofArray[0].push(daof.getMonth() + 1 + '月' + daof.getDate() + '日');
      }
      for(let j = 9; j < 21; j++){
        dateofArray[1].push(((j.length == 1 ? "0" + j : j) + ':00-' + ((j.length == 1 ? "0" + j : j) + 1) + ':00'))
      }
      app.globalData.yun_price = '0.00';
      self.setData({ yun_price: '0.00'})
      const _all_price = +self.data.all_price, _yun_price = +self.data.yun_price, yhj = +self.data.yhj, yhje = +self.data.yhje;
      self.updateQrdd(_all_price, "", 0, (+_all_price) - (_yun_price) - yhj - yhje)
      self.setData({
        dateof:dateofArray,
        shipshow: false,
        dateshow:true,
        fpinput: '配送时间 ' + dateofArray[0][self.data.pickerVal[0]] + ' ' + dateofArray[1][self.data.pickerVal[1]],
      })
    }
    
  },
  /**/
  bindPickerSince(res){
    this.setData({
      shipContextIndex: res.detail.value | 0
    })
  },
  bindChangedateof(res){
    this.setData({
      pickerVal: [res.detail.value[0], res.detail.value[1]],
      fpinput: '配送时间 ' + this.data.dateof[0][res.detail.value[0]] + ' ' + this.data.dateof[1][res.detail.value[1]]
    })
  },
  switch1Change(res){    
      this.setData({
        faShow: res.detail.value ? true : false
      })    
  },
  radioChange(res){
    this.data.fptoggle = res.detail.value;
  },
  /*订单备注信息*/ 
  bindfpchange(res){
    this.setData({
      fpinput:res.detail.value
    })
  },
  qrdd_end_jg(){
    const self = this;
    var _all_price = +app.globalData.all_price;
    var _qrdd_yhje = +app.globalData.yhje;
    var _qrdd_yhj = +app.globalData.yhj;
    var _yun_price = +app.globalData.yun_price;
    var _qrdd_jfdk = 0;
    if (app.globalData._by) {
      _yun_price = 0;
      _qrdd_yhj = 0;
    } else {
      _qrdd_yhj = parseFloat(_qrdd_yhj);
    }
    if (parseFloat(_all_price - _qrdd_yhje - _qrdd_yhj + _yun_price) <= 0) {
      wx.showToast({
        title: '结算异常',
        icon: 'success',
        duration: 2000
      })
    } else {
      app.globalData.orderallprice = (_all_price - _qrdd_yhje - _qrdd_yhj + _yun_price - _qrdd_jfdk).toFixed(2)
      self.setData({
        orderallprice: app.globalData.orderallprice
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      duration: 10000
    })
    const self = this;
    this.data._dzname = "";
    /*加载支付方式*/
    if (app.globalData['yyyyy']) {
      this.setData({
        orderallprice: app.globalData.orderallprice,
        all_price: app.globalData.all_price,
        yhje: app.globalData.yhje,
        yhj: app.globalData.yhj,
        kg: app.globalData.kg,
        yun_price: app.globalData.yun_price,
        yhjtext: app.globalData.yhjtext
      })
      wx.hideLoading()
        return;
    }
    if (app.globalData['nt'] && app.globalData['nt'] !== "2"){
      this.setData({
        _dzname: app.globalData._dzname,
        addressId: app.globalData.addressId,
        _dzphone: app.globalData._dzphone,
        _dzaddress: app.globalData._dzaddress,
        prov: app.globalData.prov,
        addtoggle: true
      })
      return;
    }else{
      app.globalData.user_yhq = "";
      self.addShipping(res => {
        self.setData({
          shipping: {
            index: res.data.map(item => item.text),
            value: res.data.map(item => item.px),
            ship: res.data[0].text
          },
          tsshow:false
        })
        self.adding(this.data.spid, (res) => {
          console.log('==========================')
          console.log(res)
          
          let g = app.globalData;
           g.zc_obj = [], 
            g.tc_obj = [],
            g.jqg_obj = [],
            g._ab_obj = null;
            g._json = res.data.goodsList;
            g._amount_obj = res.data.amount_limit;
            self.setData({ _amount_obj: g._amount_obj});
            g._json = res.data.goodsList;
            g.tc_json = res.data.packageList;
            g.jqg_json = res.data.redemption;
            g.yhqArr = [];
            if (+(res.data.allJf) > 0){
              self.setData({
                ts: `可用${res.data.allJf}积分抵扣`,
                tsshow:true
              })
            }else{
              self.setData({
                ts: ``,
                tsshow: false
              })
            }
            g.exp = res.data.exp;
            g.cityDistribution =res.data.tcps;
            let buying = []
            var tc_num = 0;//
            var sp_num = 0;//
            var jqg_num = 0;//
            var html = '';
            var _j = 0;
            var tc_j = 0;
            var jqg_j = 0;
            var _w = 0;
            var cxjg = 0;
            var isNllcx = 0;
            var cxjson = res.data.rule;
            g.cxjson = cxjson;
            var tccomm = [], jqgcomm = [],comm = [], red = [], full = [];
            g._ab_obj = res.data.rule;
            self.setData({ _ab_obj: res.data.rule });
            if (g.tc_json){
              for (let i = 0; i < g._json.length; i++){
                if (g._json[i][2] == true) {
                  sp_num++;
                }
              }
            }
            
            if(g.tc_json){
              for (let i = 0; i < g.tc_json.length; i++){
                if (g.tc_json[i].chk ==  1){
                  let tc_price = (g.tc_json[i].packageprice).toFixed(2);
                  g.tc_json[i].tc_price = +(tc_price);
                  tc_num++;
                  tc_j = parseFloat(tc_j) + ((parseFloat(tc_price) * 100) * parseFloat(g.tc_json[i].packageNum));
                  tccomm.push(g.tc_json[i]);
                  g.tc_obj.push({
                    packageId: g.tc_json[i].packageId,
                    packageName: g.tc_json[i].packageName,
                    packageNum: g.tc_json[i].packageNum,
                    packageprice: tc_price,
                    assemblyImage: g.tc_json[i].assemblyImage
                  });
                }
              }
              self.setData({
                tccomm: tccomm
              })
            }
            
            if(g.jqg_json){
              for (let i = 0; i < g.jqg_json.length;i++){
                
                if (g.jqg_json[i].chk == 1) {
                  var jqg_price = (g.jqg_json[i].exchangePrice).toFixed(2);
                  
                  g.jqg_json[i].jqg_price = +(jqg_price)
                  jqg_num++;
                  jqg_j = parseFloat(jqg_j) + ((parseFloat(jqg_price) * 100) * parseFloat(g.jqg_json[i].userQuota));
                  
                  jqgcomm.push(g.jqg_json[i])
                  g.jqg_obj.push({
                    _id: g.jqg_json[i]._id,
                    userQuota: g.jqg_json[i].userQuota,
                    spmc: g.jqg_json[i].spmc,
                    exchangePrice: jqg_price,
                    sptm: g.jqg_json[i].sptm
                  })
                }
              }
              
              self.setData({
                jqgcomm: jqgcomm/*加钱购 */
                
              })
            }
            
            for (let k = 0; k < g.cxjson.length; k++){
              let kt = { comm: [] }
              console.log(cxjson[k])
              if (g.cxjson[k][0] == "123456789") {
                if (k > 0) {
                  
                }
                if (g.cxjson[k][5] == "无促销") {
                } else {
                }
              }else{
                kt.rule = g.cxjson[k];
                cxjg += parseFloat((g.cxjson[k][2]).toFixed(2))
              }
              for (let i = 0; i < g._json.length; i++) {

                if (g._json[i][2] == true) {
                  if (!g._json[i][0].type) {
                    if (g._json[i][1].length > 0) {
                      for (var kk = 0; kk < g._json[i][1].length; kk++) {
                        if (g._json[i][1][kk][2] == true) {
                          if (g.cxjson[k][0] == g._json[i][1][kk][0]._id) {
                            var sp_price = (g._json[i][3]).toFixed(2);
                            var _sp_price = (g._json[i][3] * (1 - g.cxjson[k][8])).toFixed(2);
                            g._json[i][0]._sp_price = _sp_price;
                            g.yhqArr[g._json[i][0].goodsId] = 1;
                            if (g._json[i][0].flid0 != "") {
                              var fl0 = (g._json[i][0].flid0).split(',')
                              for (var f = 0; f < fl0.length; f++) {
                                g.yhqArr[fl0[f]] = 1;
                              }
                            }
                            if (g._json[i][0].flid1 != "") {
                              var fl1 = (g._json[i][0].flid1).split(',')
                              for (var f = 0; f < fl1.length; f++) {
                                g.yhqArr[fl1[f]] = 1;
                              }
                            }
                            if (g._json[i][0].flid2 != "") {
                              var fl2 = (g._json[i][0].flid2).split(',')
                              for (var f = 0; f < fl2.length; f++) {
                                g.yhqArr[fl2[f]] = 1;
                              }
                            }
                            kt.comm.push(g._json[i][0])
                            _j += ((parseFloat(sp_price) * 100) * parseFloat(g._json[i][0].num));
                            _w = parseFloat(_w) + ((parseFloat(g._json[i][0].weight) * 100) * parseInt(g._json[i][0].num));
                            g.zc_obj.push({
                              spid: g._json[i][0].goodsId,
                              spsl: g._json[i][0].num,
                              spbh: g._json[i][0].spbh,
                              rule_id: g.cxjson[k][0],
                              rule_name: g.cxjson[k][4],
                              rule_count: parseFloat(g.cxjson[k][3]).toFixed(2),
                              rule_preferential: parseFloat(g.cxjson[k][2]).toFixed(2)
                            });
                          }
                        }
                      }
                    }
                    if (g.cxjson[k][0] == "123456789"){
                      if (g._json[i][1].length == 0){
                        var sp_price = (g._json[i][3]).toFixed(2);
                        g.yhqArr[g._json[i][0].goodsId] = 1;
                        if (g._json[i][0].flid0 != "") {
                          var fl0 = (g._json[i][0].flid0).split(',')
                          for (var f = 0; f < fl0.length; f++) {
                            g.yhqArr[fl0[f]] = 1;
                          }
                        }
                        if (g._json[i][0].flid1 != "") {
                          var fl1 = (g._json[i][0].flid1).split(',')
                          for (var f = 0; f < fl1.length; f++) {
                            g.yhqArr[fl1[f]] = 1;
                          }
                        }
                        if (g._json[i][0].flid2 != "") {
                          var fl2 = (g._json[i][0].flid2).split(',')
                          for (var f = 0; f < fl2.length; f++) {
                            g.yhqArr[fl2[f]] = 1;
                          }
                        }
                        _j += ((parseFloat(sp_price) * 100) * parseFloat(g._json[i][0].num));
                        _w = parseFloat(_w) + ((parseFloat(g._json[i][0].weight) * 100) * parseInt(g._json[i][0].num));
                        g._json[i][0].sp_price = sp_price;
                        kt.comm.push(g._json[i][0])
                        g.zc_obj.push({
                          spid: g._json[i][0].goodsId,
                          spsl: g._json[i][0].num,
                          spbh: g._json[i][0].spbh,
                          rule_id: '',
                          rule_name: '',
                          rule_count: (parseFloat(g._json[i][0].price) * parseInt(g._json[i][0].num)).toFixed(2),
                          rule_preferential: 0
                        });
                        isNllcx++;
                      }
                    }
                  }
                }
              }
              if (g.cxjson[k][5] == "满赠"){
                kt.zp = []; kt.zp2 = [];
                for (let i = 0; i < g.cxjson[k][6].length; i++){
                  kt.zp.push(g.cxjson[k][6][i])
                }
                for (let i = 0; i < g.cxjson[k][7].length; i++) {
                  kt.zp2.push(g.cxjson[k][7][i])
                }
              }
              if (g.cxjson[k][0] == "123456789") {
                
                if (g.cxjson[k][5] == "无促销") {
                  comm.push(kt)
                 
                }else{
                  comm.push(kt)
                }
              } else {
                console.log(kt)
                if (g.cxjson[k][5] == '满赠') {
                  full.push(kt)
                } else {
                  red.push(kt)
                }
              }
              
            }
            
            for (let i = 0; i < g._json.length;i++){
              if (g._json[i][2] == true) {
                if (g._json[i][0].type) {
                  buying.push(g._json[i])
                  _j += ((parseFloat(g._json[i][0].spxsj) * 100) * parseFloat(g._json[i][0].num));
                  _w = parseFloat(_w) + ((parseFloat(g._json[i][0].weight) * 100) * parseInt(g._json[i][0].num));
                  g.zc_obj.push({
                    spid: g._json[i][0].goodsId,
                    spsl: g._json[i][0].num,
                    spbh:g._json[i][0].spbh,
                    rule_id: "",
                    rule_name: "",
                    rule_count: 0,
                    rule_preferential: 0,
                    type: g._json[i][0].type,
                  });
                }
              }
            }
            if (tc_j > 0 || jqg_j > 0) {
              _j = (parseFloat(_j) + parseFloat(tc_j) + parseFloat(jqg_j));
            }

            if (g.tc_json || g.jqg_json){
                self.setData({
                  nm: parseInt(sp_num) + parseInt(jqg_num) + parseInt(tc_num)
                })
            }else{
              self.setData({
                nm: sp_num
              })
            } 
            g.all_price = parseFloat(_j / 100).toFixed(2);
            g.kg = parseFloat(_w / 100).toFixed(2)
            self.setData({
              all_price: parseFloat(_j / 100).toFixed(2),
              kg: parseFloat(_w / 100).toFixed(2)
            })
            if (parseFloat(res.data.userInfo.wallet) > 0){
              self.setData({
                money_dkNum: parseFloat(_j / 100) >= res.data.userInfo.wallet ? parseFloat(res.data.userInfo.wallet).toFixed(2) : parseFloat(_j / 100).toFixed(2),
                money_dk:true,
                money_dkNumNone: parseFloat(_j / 100) >= res.data.userInfo.wallet ? parseFloat(res.data.userInfo.wallet).toFixed(2) : parseFloat(_j / 100).toFixed(2)
              })
            }else{
              self.setData({
                money_dkNum: 0,
                money_dk: false,
                money_dkNumNone:0
              })
            }
            var amount_jg = parseFloat(_j / 100) - cxjg;
            console.log(amount_jg >= Number(g._amount_obj.money))
            if (g._amount_obj == '') {
              g._amount_obj = '';
              self.setData({ _amount_obj:""})
            }
            if (amount_jg >= Number(g._amount_obj.money)){
              g._amount_obj = '';
              self.setData({ _amount_obj: "" })
            } 
            console.log(g._amount_obj)
            self.setData({
              yhje: cxjg,
              tccomm: tccomm,
              jqgcomm: jqgcomm,
              comm: comm, 
              buying:buying,
              full: full,
              red:red
            })
            g.yhje = cxjg
            self.qrdd_end_jg()
            
            self.addAddress(self.data._dzname, (res) => {
              if (res.data.length) {
                for (let i of res.data) {
                  if (i.isuse) {
                    app.globalData._dzname = i.name;
                    app.globalData.addressId = i.id;
                    app.globalData._dzphone = i.phone;
                    app.globalData._dzaddress = `${i.prov}${i.city}${i.district}${i.address}`;
                    app.globalData.prov = i.prov;
                    self.setData({
                      yhjtext: app.globalData.yhjtext,
                      _dzname: app.globalData._dzname,
                      addressId: app.globalData.addressId,
                      _dzphone: app.globalData._dzphone,
                      _dzaddress: app.globalData._dzaddress,
                      prov: app.globalData.prov,
                      addtoggle: true
                    })
                    wx.hideToast()
                    self.sb(+self.data.kg, result => {
                      console.log(result)
                      self.setData({
                        shipshow: false,
                        dateshow: false,
                        fpinput: ""
                      })
                    })
                    return;
                  } else {
                    app.globalData._dzname = i.name;
                    app.globalData.addressId = i.id;
                    app.globalData._dzphone = i.phone;
                    app.globalData._dzaddress = `${i.prov}${i.city}${i.district}${i.address}`;
                    app.globalData.prov = i.prov;
                    self.setData({
                      _dzname: app.globalData._dzname,
                      addressId: app.globalData.addressId,
                      _dzphone: app.globalData._dzphone,
                      _dzaddress: app.globalData._dzaddress,
                      prov: app.globalData.prov,
                      addtoggle: true
                    })
                    wx.hideToast()
                  }
                }
              }
              self.sb(+self.data.kg, result => {
                self.setData({
                  shipshow: false,
                  dateshow: false,
                  fpinput: ""
                })
              })
            })
            setTimeout(function(){
              console.log(g.orderallprice)
            },2000)
        
      })
      })
    }  
    
  },
  /*价格赋值 */
  updateQrdd(all_price, qrdd_yhje, yun_price, order_all_price){
    let g = app.globalData;
    if (all_price == "") {
    } else {
      g.all_price = all_price.toFixed(2);
      this.setData({ all_price: all_price.toFixed(2)});
    }
    if (qrdd_yhje == "") {
    } else {
      g.yhje = qrdd_yhje;
      this.setData({ yhje: qrdd_yhje.toFixed(2) });
    }
    if (yun_price == "") {
    } else {
      g.yun_price = yun_price.toFixed(2);
      this.setData({ yun_price: yun_price.toFixed(2) });
    }
    if (order_all_price == "") {
    } else {
      g.orderallprice = order_all_price.toFixed(2);
      this.setData({ orderallprice: order_all_price.toFixed(2) });
    }

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})